<!--  费用活动申请-->
<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />

    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        v-bind='vexConfig'
        :align='left'
        :border='true'
        :checkbox-config='checkboxConfig'
        :columns='columns'
        :data='dataSource'
        :height='pageHeight-seachHeight-94'
        :loading='loading'
        :resizable='true'
        :showOverflow='true'
        :toolbar-config='tableToolbar'
        size='mini'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class="flex" style="display: flex;justify-content: space-between;align-items: center">
            <!-- 操作按钮区域 -->
            <div class='table-operator'>
              <a-button v-has="'apllcation:add'" type='primary' @click='handleAdd'>新增</a-button>
              <a-button v-has="'apllcation:delete'" :disabled='deletBut' type='primary' @click='batchDel'>删除</a-button>
              <a-button v-has="'apllcation:close'" type='primary' @click='handleClose'>活动关闭</a-button>
              <a-button v-has="'apllcation:getOut'" type='primary' @click="downExportXls('activity_service')">
                导出
              </a-button>
              <a-button v-has="'apllcation:getCateOut'" type='primary' @click="downExportXls('act_category_statistics_service')">
                申请细类导出
              </a-button>
              <a-button type='primary' @click='handleAppdatarove' :disabled="selectionRows.length!=1||selectionRows[0].bpmStatus!=2">活动审批</a-button>
              <a-button v-has="'apllcation:audient'" type='primary' @click='handleApprove'>模拟审批</a-button>
              <a-button v-has="'apllcation:check'" type='primary' @click='handleRedeal'>自动审核</a-button>
            </div>
<!--            <div class='moreData'>-->
<!--              <div class='moreData-box'>-->
<!--                <span style='fontWeight:700'>申请金额:</span>-->
<!--                <span style='margin:12px 0'>当页合计: {{ moneyData.pagePriceAmount || '暂无' }}</span>-->
<!--                <span>总合计:{{ moneyData.totalAmount || '暂无' }}</span>-->
<!--              </div>-->
<!--            </div>-->
          </div>
        </template>
        <template #actCode='{ row,rowIndex }'>
          <a v-has="'apllcation:detail'" @click='handleEdit(row,"detail")'>{{ row.actCode }}</a>
        </template>
        <template #action='{ row:record }'>
          <a v-if='record.endActIsChange == 1' v-has="'apllcation:edit'" @click='handleEdit(record)'>编辑</a>
        </template>

        <template #pager>
          <vxe-pager
            :currentPage.sync='ipagination.current'
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :page-size.sync='ipagination.pageSize'
            :pageSizes='ipagination.pageSizeOptions'
            :total='ipagination.total'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <div class='moreData'>

      <!--      <div class='moreData-box'>-->
      <!--        <span style='fontWeight:700'>上账金额:</span>-->
      <!--        <span style='margin:12px 0'>当页合计:{{ dataSource.pageFeePayAmount }}</span>-->
      <!--        <span>总合计:{{ dataSource.feePayTotalAmount }}</span>-->
      <!--      </div>-->
    </div>
    <applicationModal ref='modalForm' @ok='modalFormOk'></applicationModal>
  </a-card>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import applicationModal from '@/views/tmr/costCenter/modules/applicationModal'
import HpayselectCom from '@/components/cn-components/HpayselectCom'
import store from '@/store'
import pick from 'lodash.pick'

export default {
  name: 'activityApplication',
  mixins: [PageListMixin],
  components: {
    applicationModal,
    HpayselectCom
  },
  data() {
    return {
      moneyData: {},
      permflag: 'tpm_act_impl',
      deletBut: false,
      loading: false,
      description: '费用活动申请',
      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'actCode',
          placeholder: '活动编码'
        }, {
          // label:'业务员',
          type: 'input',
          name: 'actName',
          placeholder: '活动名称'
        }, {
          // label:'订单状态',
          type: 'j-select',
          name: 'bpmStatus',
          dictCode: 'bpm_status',
          placeholder: '审批状态'
        }, {
          // label:'售达方编码',
          type: 'date-range',
          name: 'kunnr',
          range: ['startDate', 'endDate'],// 后台接受字段
          placeholder: ['开始时间', '结束时间']
        }, {
          type: 'tree-select',
          placeholder: '申请人组织',
          dataType: 'org',
          name: 'orgCode'  // 后台接受字段
        }, {
          // label:'出库时间',
          type: 'input',
          name: 'createBy',
          placeholder: '申请人姓名'
        },
        {
          // label:'出库时间',
          type: 'input',
          name: 'actObjectName',
          placeholder: '活动对象'
        },

      ],
      // 表头
      columns: [
        { type: 'checkbox', width: 50, fixed: null ,field: 'a',},
        {
          title: '活动编码',
          field: 'actCode',
          minWidth: 120,
          slots: { default: 'actCode' }
        },
        {
          title: '活动名称',
          field: 'actName',
          minWidth: 80,
        },
        {
          title: '流程编号',
          minWidth: 80,
          field: 'processKey'
        },
        {
          title: '审批状态',
          minWidth: 80,
          field: 'bpmStatusStr'
        },
        {
          title: '申请金额',
          minWidth: 80,
          field: 'totalAmount'
        },
        {
          title: '活动开始时间',
          minWidth: 100,
          field: 'startDate'
        },
        {
          title: '活动结束时间',
          minWidth: 100,
          field: 'endDate'
        },
        {
          title: '创建人',
          minWidth: 90,
          field: 'createName'
        },
        {
          title: '创建人所在组织名称',
          minWidth: 130,
          field: 'createByOrgName'
        },
        {
          title: '活动对象',
          minWidth: 80,
          field: 'actObjectName'
        },
        {
          title: '关闭原因',
          minWidth: 80,
          field: 'closingInstructions'
        },
        {
          title: '创建时间',
          minWidth: 120,
          field: 'createTime'
        },
        {
          title: '更新人',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          minWidth: 120,
          field: 'updateTime'
          // customRender:(t,r,index)=>{
          //   if(r.updateDate!=null){
          //     return r.updateDate +'-'+ r.updateDateTime
          //   }
          // }
        },
        {
          title: '操作',
          field: 'action',
          fixed: 'right',
          width: 80,
          slots: { default: 'action' }
        }
      ],
      url: {

        deals: window._CONFIG['domianTpmURL'] + '/tpmAudit/autoBuildAudit',
        list: window._CONFIG['domianTpmURL'] + '/activity/findPageList',
        detail: window._CONFIG['domianTpmURL'] + '/activity/findOne',
        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        closeOne: window._CONFIG['domianTpmURL'] + '/activity/closeActivity',
        deleteBatch: window._CONFIG['domianTpmURL'] + '/activity/delete',
        app: window._CONFIG['domianTpmURL'] + '/activity/auditBpm',
        appdata:window._CONFIG['domianTpmURL'] + '/workrequest/updateActProcess',
      },
      closeReason: '',
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  methods: {
    loadData(arg) {
      if (!this.url || !this.url.list) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件
      console.log(params)
      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          let {
            records = [],
            total
          } = res.result
          if (!isNoPagnation) that.ipagination.total = total || 0
          let a = res.result
          that.ipagination.current = a.current || 0
          that.ipagination.total = a.total || 0
          that.dataSource = res.result.records
          that.moneyData = pick(res.result, 'pagePriceAmount', 'totalAmount')
        } else {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
      // }
    },
    getStore() {
      console.log(store.state.testState)
    },
    handleRedeal() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.info('请至少选择一项')
        return
      }
      let ids = ' '
      let that = this
      ids = this.selectedRowKeys.join(',').toString()
      getAction(that.url.deals, { ids: ids }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleApprove() {
      if (this.selectedRowKeys.length != 1) {
        this.$message.warning('请选择一条记录！')
        return
      }
      let that = this
      that.loading = true
      getAction(that.url.app, { id: that.selectedRowKeys + '', bpmStatus: 3 }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.loading = false
      })
    },
    handleAppdatarove: async function(record, status) {
      if (this.selectedRowKeys.length != 1) {
        this.$message.warning('请选择一条记录！')
        return
      }
      console.log(this.selectionRows)
      let that = this
      // that.loading = true
        let cods = JSON.parse(JSON.stringify(record))
        const res = await getAction(this.url.detail, { id: that.selectedRowKeys + '' })
        if (res.success) {
          record = res.result
          record.bpmStatus = 4
          this.$refs.modalForm.edit(record)
          this.$refs.modalForm.title = '审批'
          this.$refs.modalForm.disableSubmit = true
          this.$refs.modalForm.saveButton = false
          this.$refs.modalForm.orgContral = true
          this.$refs.modalForm.appdata=true
        } else {
          this.$message.error(res.message)
        }
      this.$refs.modalForm.disableSubmit = false
    },
    handleClose: function() {
      let that = this
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        let ids = this.selectedRowKeys[this.selectedRowKeys.length - 1]
        this.$confirm({
          title: `是否关闭 [ ${this.selectionRows[this.selectedRowKeys.length - 1].actName} ] ?`,
          content: this.$createElement('a-input', {
            attrs: {
              placeholder: '请输入关闭原因'
            },
            domProps: {
              value: that.closeReason || '',
              type: 'text'
            },
            on: {
              input: function(e) {
                that.closeReason = e.target.value
              }
            }
          }),
          // '是否关闭选中数据?'
          onOk: function() {
            if (that.closeReason == '') {
              that.$message.info('请输入关闭原因')
              return Promise.reject()
            } else {
              that.loading = true
              getAction(that.url.closeOne, { id: ids, closingInstructions: that.closeReason }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
                that.closeReason = ''
              })
            }
          }
        })
      }
    },
    handleEdit: async function(record, status) {
      let cods = JSON.parse(JSON.stringify(record))
      if (status == 'detail') {
        const res = await getAction(this.url.detail, { id: record.id })
        if (res.success) {
          record = res.result
          record.bpmStatus = 4
          this.$refs.modalForm.edit(record)
          this.$refs.modalForm.title = '详情'
          this.$refs.modalForm.disableSubmit = true
          this.$refs.modalForm.saveButton = false
          this.$refs.modalForm.orgContral = true
        } else {
          this.$message.error(res.message)
        }
      } else {
        const res = await getAction(this.url.detail, { id: record.id, change: 1 })
        if (res.success) {
          record = res.result
          this.$refs.modalForm.edit(record)
          if (cods.bpmStatus == 1) {
            this.$refs.modalForm.saveButton = true
          } else {
            this.$refs.modalForm.saveButton = false
          }
          this.$refs.modalForm.title = '编辑'
          this.$refs.modalForm.disableSubmit = false
        } else {
          this.$message.error(res.message)
        }
      }
    }
  },
  created() {
    this.queryParam.doc = '订货单'

  },


  // beforeMount() {
  //   const draggingMap = {};
  //   this.columns.forEach((col) => {
  //     draggingMap[col.field] = col.width;
  //   });
  //   const draggingState = Vue.observable(draggingMap);
  //   const resizeableTitle = (h, props, children) => {
  //     let thDom = null;
  //     const { key, ...restProps } = props;
  //     console.log(props)
  //     let col;
  //     // 复选框筛选处理
  //     if (key === 'selection-column') {
  //       col = {};
  //     } else {
  //       col = this.columns.find((item) => {
  //         const k = item.field || item.key;
  //         return k === key;
  //       });
  //     }
  //     // 未设置宽度或者设置不可伸缩时不做伸缩处理
  //     if (!col.width || col.noStretch) {
  //       return <th {...restProps}>{children}</th>;
  //     }
  //     const onDrag = (x) => {
  //       draggingState[key] = 0;
  //       // 设置一个伸缩的最小宽度，防止页面错乱
  //       col.width = Math.max(x, col.minWidth || 30);
  //     };
  //     const onDragstop = () => {
  //       draggingState[key] = thDom.getBoundingClientRect().width;
  //     };
  //     return (
  //       <th
  //         {...restProps}
  //         v-ant-ref={(r) => (thDom = r)}
  //         width={col.width}
  //         class="resize-table-th"
  //       >
  //         {children}
  //         <vue-draggable-resizable
  //           key={col.key}
  //           class="table-draggable-handle"
  //           w={10}
  //           x={col.width||draggingState[key]}
  //           z={1}
  //           axis="x"
  //           draggable={true}
  //           resizable={false}
  //           onDragging={onDrag}
  //           onDragstop={onDragstop}
  //         />
  //       </th>
  //     );
  //   };
  //   this.components = {
  //     header: {
  //       cell: resizeableTitle,
  //     },
  //   };
  // },


  watch: {
    selectionRows: {
      deep: true,
      handler(val) {
        if (val.length !== 0) {
          let index = val.findIndex(v => v.bpmStatus != 1)
          if (index == -1) {
            this.deletBut = false
          } else {
            this.deletBut = true
          }
        } else {
          this.deletBut = false
        }
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      }
    }
  }
}
</script>

<style lang='less' scoped>
@import '~@assets/less/common.less';

/deep/ .ant-pagination {
  float: right;
}

///deep/ .resize-table-th {
//  position: relative;
//}
///deep/ .table-draggable-handle {
//  height: 100% !important;
//  bottom: 0;
//  left: auto !important;
//  right: -5px;
//  cursor: col-resize;
//  touch-action: none;
//}

.moreData-box {
  display: flex;
  margin-left: 12px;
  align-items: center;
  gap: 30px;
}



</style>